import React, { useEffect } from 'react';
import styles from './ollamaTest.module.scss';
import ollamaTestStore from './ollamaTestStore';
import { observer } from 'mobx-react-lite';
import { toJS } from 'mobx';
import { ChatMessage } from '@/types/type';
import { Button, Card, Space, Typography, message, Input, Tabs, Alert, List, Modal } from 'antd';
import { SearchOutlined, ReloadOutlined, SendOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;
const { TabPane } = Tabs;

interface Iprops { }

// 组件函数不要使用React.FC类型注解
const OllamaTest = observer((props: Iprops) => {
    // 从store中获取状态值
    const { searchModels, isLoading, isInstalling, error, chatMessages, userInput, selectedModel, modelTab, searchQuery } = ollamaTestStore;
    const models = toJS(ollamaTestStore.models || []);

    // 调用Ollama模型
    const callOllamaModel = async () => {
        try {
            await ollamaTestStore.sendMessage();
            message.success('消息发送成功');

            // 滚动到底部
            setTimeout(() => {
                const chatElement = document.querySelector(`.${styles.chatMessages}`);
                if (chatElement) {
                    chatElement.scrollTop = chatElement.scrollHeight;
                }
            }, 100);
        } catch (error) {
            console.error('Error calling model:', error);
        }
    };

    // 获取Ollama本地模型列表的函数
    const getOllamaModels = async () => {
        try {
            await ollamaTestStore.loadLocalModels();
            message.success('模型列表加载成功');
        } catch (error) {
            console.error('Error fetching Ollama models:', error);
        }
    };

    // 搜索可用的Ollama模型
    const searchOllamaModels = async () => {
        try {
            await ollamaTestStore.searchModelList();
            message.success('搜索完成');
        } catch (error) {
            console.error('Error searching models:', error);
        }
    };

    // 安装Ollama模型
    const installOllamaModel = async (modelName: string) => {
        try {
            await ollamaTestStore.installModel(modelName);
            message.success(`模型 ${modelName} 安装成功！`);
        } catch (error) {
            console.error('Error installing model:', error);
        }
    };

    // 添加清空上下文的函数
    const clearChatContext = () => {
        Modal.confirm({
            title: '确定要清空当前对话上下文吗？',
            onOk() {
                ollamaTestStore.clearChatMessages();
                message.success('对话上下文已清空');
            },
        });
    };

    // 组件挂载时获取模型列表
    useEffect(() => {
        getOllamaModels();
    }, []);

    return (
        <div className={styles.content}>
            {/* PC端页面标题区域 - 参考 PageTemplate 风格 */}
            <div className={styles.header}>
                <Title level={4} className={styles.pageTitle}>Ollama 模型管理</Title>
                <Text>本地大语言模型管理与对话界面</Text>
            </div>

            {/* 左右布局容器 */}
            <div className={styles.layoutContainer}>
                {/* 左侧：模型列表 */}
                <Card className={styles.modelsPanel} title="大模型管理" variant="outlined">
                    {/* 切换菜单 */}
                    <Tabs
                        activeKey={modelTab}
                        onChange={(key) => ollamaTestStore.setModelTab(key as 'local' | 'search')}
                        className={styles.modelTabs}
                    >
                        <TabPane tab="本地大模型" key="local" />
                        <TabPane tab="搜索可用大模型" key="search" />
                    </Tabs>

                    {/* 搜索区域 */}
                    {modelTab === 'search' && (
                        <div className={styles.searchArea}>
                            <Input
                                value={searchQuery}
                                onChange={(e) => ollamaTestStore.setSearchQuery(e.target.value)}
                                placeholder="输入模型名称搜索..."
                                prefix={<SearchOutlined />}
                                className={styles.searchInput}
                                disabled={isLoading}
                            />
                            <Button
                                type="primary"
                                icon={<SearchOutlined />}
                                onClick={searchOllamaModels}
                                disabled={isLoading}
                            >
                                {isLoading ? '搜索中...' : '搜索'}
                            </Button>
                        </div>
                    )}

                    {/* 本地模型刷新按钮 */}
                    {modelTab === 'local' && (
                        <Button
                            type="primary"
                            icon={<ReloadOutlined />}
                            onClick={getOllamaModels}
                            className={styles.testButton}
                            disabled={isLoading}
                        >
                            {isLoading ? '刷新中...' : '刷新模型'}
                        </Button>
                    )}

                    {error && (
                        <Alert
                            message="错误"
                            description={error}
                            type="error"
                            showIcon
                            className={styles.error}
                        />
                    )}

                    {/* 模型列表内容 */}
                    {modelTab === 'local' ? (
                        models.length > 0 ? (
                            <div className={styles.modelsList}>
                                <List
                                    dataSource={toJS(models)}
                                    renderItem={(model) => (
                                        <List.Item
                                            className={`${styles.modelItem} ${selectedModel === model.name ? styles.selectedModel : ''}`}
                                            onClick={() => ollamaTestStore.setSelectedModel(model.name)}
                                            actions={[
                                                <Text key="1">{Math.round(model.size / (1024 * 1024))} MB</Text>,
                                                <Text key="2">{new Date(model.modified_at).toLocaleString()}</Text>
                                            ]}
                                        >
                                            <List.Item.Meta
                                                title={<div className={styles.modelName}>{model.name}</div>}
                                                description=""
                                            />
                                        </List.Item>
                                    )}
                                />
                            </div>
                        ) : (
                            <Alert
                                message="未找到模型"
                                description="请确保Ollama已启动"
                                type="info"
                                showIcon
                                className={styles.noModels}
                            />
                        )
                    ) : (
                        searchModels.length > 0 ? (
                            <div className={styles.modelsList}>
                                <List
                                    dataSource={toJS(searchModels)}
                                    renderItem={(model) => (
                                        <List.Item
                                            className={styles.modelItem}
                                            actions={[
                                                <Button
                                                    key="install"
                                                    type="primary"
                                                    size="small"
                                                    icon={<DownloadOutlined />}
                                                    onClick={() => installOllamaModel(model.model)}
                                                    disabled={isInstalling}
                                                >
                                                    {isInstalling ? '安装中...' : '安装'}
                                                </Button>
                                            ]}
                                        >
                                            <List.Item.Meta
                                                title={<div className={styles.modelName}>{model.name}</div>}
                                                description={
                                                    <div className={styles.modelDetails}>
                                                        家族: {model.family} | 星标: {model.stars} | 下载: {model.downloads}
                                                    </div>
                                                }
                                            />
                                        </List.Item>
                                    )}
                                />
                            </div>
                        ) : (
                            <Alert
                                message="未搜索到模型"
                                description="请尝试其他关键词"
                                type="info"
                                showIcon
                                className={styles.noModels}
                            />
                        )
                    )}
                </Card>

                {/* 右侧：对话功能 */}
                <Card className={styles.chatPanel} title="模型对话" variant="outlined">
                    <div className={styles.currentModelInfo}>
                        <Text strong>当前使用模型: </Text>
                        <Text type="success">{selectedModel}</Text>
                    </div>
                    <div className={styles.chatContainer}>
                        <div className={styles.chatMessages}>
                            {toJS(chatMessages).map((msg, index) => (
                                <div
                                    key={index}
                                    className={`${styles.message} ${styles[msg.role]}`}
                                >
                                    <div className={styles.role}>
                                        <Text strong>{msg.role === 'user' ? '你' : 'AI'}:</Text>
                                    </div>
                                    <div className={styles.content}>{msg.content}</div>
                                </div>
                            ))}

                            {/* 加载状态显示 */}
                            {isLoading && (
                                <div className={styles.loadingState}>
                                    <div className={styles.loadingIcon}></div>
                                    <div className={styles.loadingText}>正在加载...</div>
                                </div>
                            )}
                        </div>

                        <div className={styles.inputArea}>
                            <Input.TextArea
                                value={userInput}
                                onChange={(e) => ollamaTestStore.setUserInput(e.target.value)}
                                placeholder="请输入对话内容..."
                                className={styles.input}
                                disabled={isLoading || isInstalling}
                                onPressEnter={callOllamaModel}
                                autoSize={{ minRows: 3, maxRows: 6 }}
                            />
                            <Space>
                                <Button
                                    type="primary"
                                    icon={<SendOutlined />}
                                    onClick={callOllamaModel}
                                    disabled={isLoading || isInstalling}
                                >
                                    {isLoading ? '发送中...' : '发送'}
                                </Button>
                                <Button
                                    icon={<DeleteOutlined />}
                                    onClick={clearChatContext}
                                    disabled={isLoading || isInstalling}
                                >
                                    清空上下文
                                </Button>
                            </Space>
                        </div>
                    </div>
                </Card>
            </div>
        </div>
    );
});

export default OllamaTest;